<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑头饰' : '新增头饰' }}</span>
        </div>
      </template>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" style="max-width: 600px">
        <el-form-item label="头饰图片" prop="imageUrl">
          <uploadImg :imageUrl="form.imageUrl" @success="uploadSuccess" @delete="deleteImage" />
          <div class="form-tip">请上传头饰图片，建议尺寸为200x200像素</div>
        </el-form-item>

        <el-form-item label="头饰名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入头饰名称" />
        </el-form-item>

        <el-form-item label="头饰分类" prop="categoryId">
          <div class="category-select">
            <el-select v-model="form.categoryId" placeholder="请选择分类" style="width: 300px">
              <el-option v-for="item in categoryOptions" :key="item._id" :label="item.name" :value="item._id">
                <div class="category-option">
                  <span>{{ item.name }}</span>
                  <el-icon color="#333" @click.stop="handleDeleteCategory(item)"><Close /></el-icon>
                </div>
              </el-option>
            </el-select>
            <el-button type="primary" @click="showCategoryDialog = true" style="margin-left: 10px">新增分类</el-button>
          </div>
        </el-form-item>

        <el-form-item label="推荐状态" prop="isRecommended">
          <el-switch v-model="form.isRecommended" active-text="推荐" inactive-text="不推荐" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" placeholder="请输入排序值" />
          <div class="form-tip">数字越小排序越靠前</div>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入头饰描述" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 新增分类弹窗 -->
    <el-dialog v-model="showCategoryDialog" title="新增分类" width="500px" :close-on-click-modal="false">
      <el-form ref="categoryFormRef" :model="categoryForm" :rules="categoryRules" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="categoryForm.sort" :min="0" :max="999" placeholder="请输入排序值" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="categoryForm.description" type="textarea" :rows="2" placeholder="请输入分类描述" maxlength="100" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCategoryDialog = false">取消</el-button>
          <el-button type="primary" @click="submitCategoryForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除分类确认弹窗 -->
    <el-dialog v-model="showDeleteDialog" title="删除分类" width="400px" :close-on-click-modal="false">
      <div class="delete-confirm">
        <el-icon class="warning-icon"><Warning /></el-icon>
        <p>
          确定要删除分类 "
          <strong>{{ selectedCategoryName }}</strong>
          " 吗？
        </p>
        <p class="warning-text">删除后无法恢复，请谨慎操作！</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDeleteDialog = false">取消</el-button>
          <el-button type="danger" @click="confirmDeleteCategory">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted, computed } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Warning, Close } from '@element-plus/icons-vue';
  import uploadImg from '@/components/uploadImg/index.vue';
  import { getHeadwearDetail, createHeadwear, updateHeadwear, getHeadwearCategories, createHeadwearCategory, deleteHeadwearCategory } from '@/api/headwear';

  const route = useRoute();
  const router = useRouter();

  const formRef = ref(null);
  const categoryFormRef = ref(null);
  const showCategoryDialog = ref(false);
  const showDeleteDialog = ref(false);
  const categoryOptions = ref([]);
  const selectedCategoryName = ref('');
  const selectedCategoryId = ref('');

  const isEdit = computed(() => route.params.id);

  const form = reactive({
    name: '',
    imageUrl: '',
    categoryId: '',
    isRecommended: false,
    sort: 0,
    description: ''
  });

  // 分类表单
  const categoryForm = reactive({
    name: '',
    sort: 0,
    description: ''
  });

  const rules = {
    name: [
      { required: true, message: '请输入头饰名称', trigger: 'blur' },
      { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    imageUrl: [{ required: true, message: '请上传头饰图片', trigger: 'change' }],
    categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }]
  };

  const categoryRules = {
    name: [
      { required: true, message: '请输入分类名称', trigger: 'blur' },
      { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
    ],
    sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }]
  };

  const getDetail = async id => {
    try {
      const response = await getHeadwearDetail(id);
      if (response.code === 200) {
        const data = response.data;
        Object.assign(form, {
          name: data.name,
          imageUrl: data.imageUrl,
          categoryId: data.categoryId,
          isRecommended: data.isRecommended,
          sort: data.sort || 0,
          description: data.description || ''
        });
      }
    } catch (error) {
      console.error('获取头饰详情失败:', error);
      ElMessage.error('获取头饰详情失败');
    }
  };

  const getCategories = async () => {
    try {
      const response = await getHeadwearCategories();
      if (response.code === 200) {
        categoryOptions.value = response.data.list;
      }
    } catch (error) {
      console.error('获取分类列表失败:', error);
    }
  };

  const uploadSuccess = imageUrl => {
    form.imageUrl = imageUrl;
  };

  const deleteImage = () => {
    form.imageUrl = '';
  };

  const handleDeleteCategory = async item => {
    selectedCategoryName.value = item.name;
    selectedCategoryId.value = item._id; // 存储要删除的分类ID
    showDeleteDialog.value = true;
  };

  const confirmDeleteCategory = async () => {
    try {
      const response = await deleteHeadwearCategory(selectedCategoryId.value);
      if (response.code === 200) {
        ElMessage.success('分类删除成功');
        showDeleteDialog.value = false;

        // 如果删除的是当前选中的分类，则清空选择
        if (form.categoryId === selectedCategoryId.value) {
          form.categoryId = '';
          ElMessage.warning('已删除当前选中的分类，请重新选择');
        }

        // 重新获取分类列表
        await getCategories();
      } else {
        ElMessage.error(response.message || '删除分类失败');
      }
    } catch (error) {
      console.error('删除分类失败:', error);
    }
  };

  const submitForm = async () => {
    if (!formRef.value) return;

    await formRef.value.validate(async valid => {
      if (valid) {
        try {
          const submitData = {
            name: form.name,
            imageUrl: form.imageUrl,
            categoryId: form.categoryId,
            isRecommended: form.isRecommended,
            sort: form.sort,
            description: form.description
          };

          let response;
          if (isEdit.value) {
            response = await updateHeadwear(route.params.id, submitData);
          } else {
            response = await createHeadwear(submitData);
          }

          if (response.code === 200) {
            ElMessage.success(isEdit.value ? '更新成功' : '创建成功');
            goBack();
          } else {
            ElMessage.error(response.msg || '操作失败');
          }
        } catch (error) {
          console.error('提交失败:', error);
        }
      }
    });
  };

  const submitCategoryForm = async () => {
    if (!categoryFormRef.value) return;

    await categoryFormRef.value.validate(async valid => {
      if (valid) {
        try {
          const response = await createHeadwearCategory({
            name: categoryForm.name,
            sort: categoryForm.sort,
            description: categoryForm.description
          });
          console.log(123, response);
          if (response.code === 200) {
            ElMessage.success('分类创建成功');
            showCategoryDialog.value = false;
            // 重置分类表单
            Object.assign(categoryForm, {
              name: '',
              sort: 0,
              description: ''
            });
            // 重新获取分类列表
            await getCategories();
          } else {
            ElMessage.error(response.msg || '创建分类失败');
          }
        } catch (error) {
          console.error('创建分类失败:', error);
        }
      }
    });
  };

  const goBack = () => {
    router.push('/headwear/list');
  };

  onMounted(async () => {
    await getCategories();
    if (isEdit.value) {
      await getDetail(route.params.id);
    }
  });
</script>

<style scoped>
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .category-select {
    display: flex;
    align-items: center;
  }

  .form-tip {
    font-size: 12px;
    color: #909399;
    margin: 0 0 0 20px;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  .delete-confirm {
    text-align: center;
    padding: 20px 0;
  }

  .warning-icon {
    font-size: 48px;
    color: #e6a23c;
    margin-bottom: 16px;
  }

  .warning-text {
    color: #f56c6c;
    font-size: 14px;
    margin-top: 8px;
  }

  .category-option {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  .delete-btn {
    margin-left: 8px;
    flex-shrink: 0;
  }
</style>
